package com.hrm.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hrm.config.JSPPage;
import com.hrm.entity.Message;
import com.hrm.entity.Reward;
import com.hrm.entity.User;
import com.hrm.service.ConfigService;
import com.hrm.service.RewardService;
import com.hrm.util.DateUtil;
import com.hrm.util.JSONUtil;
import com.hrm.util.Page;


@Controller
@RequestMapping("/reward.do")
public class RewardAction {
	private static final Log log = LogFactory.getLog(RewardAction.class); 
	@Autowired
	private RewardService rewardService; 
	@Autowired
	private ConfigService configService; 
	public ConfigService getConfigService() {
		return configService;
	}
	public void setConfigService(ConfigService configService) {
		this.configService = configService;
	}
	public RewardService getRewardService() {
		return rewardService;
	}
	public void setRewardService(RewardService rewardService) {
		this.rewardService = rewardService;
	}
	@RequestMapping(params = "method=getRewards")
	public String getRewards(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		//获取所有数据的前15条数据
		Page page = new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		Map<String, Object> searchMap = new HashMap<String, Object>();
		if("true".equals(request.getParameter("_search"))){
			searchMap.put(request.getParameter("searchField"),request.getParameter("searchString"));
		}
		List<Reward> rewards = rewardService.getRewards(page);
		page.setCounts(rewardService.getRewardCounts());
		if(rewards!=null){
			log.info("begin to getRewards");
			try {
				Map<String, Object> resultMap2 = new HashMap<String, Object>();
				resultMap2.put("page", page.getCurrentpage()+"");
				log.debug("currentpage="+page.getCurrentpage());
				log.debug("countpage="+page.getCountPage());
				log.debug("records="+page.getCounts());
				resultMap2.put("total", page.getCountPage()+"");
				resultMap2.put("records", page.getCounts()+"");
				List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
				for(Reward u:rewards){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					//配置实现表格超链接
					list.add(u.getRewardName()+"");
					list.add(u.getRewardType().getConfigName()+"");
					list.add(u.getRewardAmount()+"");
					list.add(u.getRewardUnit());
					list.add(u.getRewardPrice()+"");
					list.add(u.getRewardTotal()+"");
					list.add(u.getRewardPurpose().getConfigName()+"");
					list.add(u.getPurchasePerson()+"");
					list.add(DateUtil.formate(u.getPurchaseTime())+"");
					list.add(u.getPurchaseSource()+"");
					list.add(u.getRemark());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap2.put("rows", rows);
				String result=JSONUtil.parseMap(resultMap2);
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!", new Date());
				System.out.println(message.toJSONString());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addReward")
	public String addReward(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		Message message = new Message();
		String rewardName=request.getParameter("rewardName")==null?"":request.getParameter("rewardName");
		int rewardAmount=Integer.parseInt(request.getParameter("rewardAmount")==null?"-1":request.getParameter("rewardAmount"));
		double rewardPrice=Double.parseDouble(request.getParameter("rewardPrice")==null?"-1.0":request.getParameter("rewardPrice"));
		//double rewardTotal=Double.parseDouble(request.getParameter("rewardTotal")==null?"-1.0":request.getParameter("rewardTotal"));
		String rewardType=request.getParameter("rewardType")==null?"":request.getParameter("rewardType");
		String rewardPurpose=request.getParameter("rewardPurpose")==null?"":request.getParameter("rewardPurpose");
		
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		if("".equals(rewardName)||rewardName.getBytes().length>=50){
			message.setMsg("福利物品名称不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(rewardAmount==-1){
			message.setMsg("福利物品总数不能为空!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(rewardPrice==-1.0){
			message.setMsg("福利物品单价不能为空!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(rewardType)||rewardType.getBytes().length>=50){
			message.setMsg("福利物品类型不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(rewardPurpose)||rewardPurpose.getBytes().length>=50){
			message.setMsg("福利物品用途不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(remark.getBytes().length>=200){
			message.setMsg("备注长度必须在200个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Reward reward = new Reward();
		//TODO判断reward的用途和类型是否已存在，如果不存在，则添加
		if(!configService.isExistConfigItem(rewardType.split(".")[0], rewardType.split(".")[1])){
			configService.addConfigItem(null);
		}
		
//		reward.setName(name);
//		reward.setCode(code);
//		reward.setUpdateTime(new Date());
//		reward.setPath(path);
//		reward.setRemark(remark);
		if(rewardService.addReward(reward)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("新增配置项成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=updateReward")
	public String updateReward(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		Reward reward = rewardService.getRewardById(id);
		if(reward==null){
			Message message = new Message();
			message.setMsg("获取配置项信息失败!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		map.put("reward", reward);
		return JSPPage.CONFIG_ITEM_EDIT;
	}
	@RequestMapping(params = "method=updateRewardById")
	public String updateRewardById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入配置项ID才能编辑!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String name=request.getParameter("name")==null?"":request.getParameter("name");
		String code=request.getParameter("code")==null?"":request.getParameter("code");
		String path=request.getParameter("path")==null?"":request.getParameter("path");
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		Message message = new Message();
		if("".equals(name)||name.getBytes().length>=20){
			message.setMsg("配置项名不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(name)||name.getBytes().length>=50){
			message.setMsg("配置项名不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(code)||code.getBytes().length>=20){
			message.setMsg("配置项编码不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(path)||path.getBytes().length>=80){
			message.setMsg("配置项编码不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(remark.getBytes().length>=200){
			message.setMsg("备注长度必须在200个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Reward reward = new Reward();
//		reward.setId((int) id);
//		reward.setName(name);
//		reward.setPath(path);
//		reward.setCode(code);
//		reward.setRemark(remark);
//		reward.setUpdateTime(new Date());
//		User user =(User) request.getSession().getAttribute("user");
//		reward.setUserId(user.getId());
//		reward.setUserName(user.getUserName());
		if(rewardService.updateReward(reward)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("编辑配置项成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=deleteRewardById")
	public String deleteRewardById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String rewardids = request.getParameter("rewardids")==null?"":request.getParameter("rewardids");
		Message message = new Message();
		if("".equals(rewardids)){
			message.setMsg("必须传入配置项ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(rewardService.deleteRewardById(rewardids)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("删除配置项成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
}
